package com.itheima.behaviour.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.behaviour.dto.FollowBehaviorDto;
import com.itheima.behaviour.mapper.ApBehaviorEntryMapper;
import com.itheima.behaviour.mapper.ApFollowBehaviorMapper;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApFollowBehavior;
import com.itheima.behaviour.service.ApFollowBehaviorService;
import com.itheima.common.constants.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description <p>APP关注行为 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.behaviour.service.impl
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    private ApBehaviorEntryMapper apBehaviorEntryMapper;
    /**
     * 保存用户行为,涉及的表有  ap_behavior_entry   行为实体表    ap_follow_behavior  APP关注行为表
     * @param followBehaviorDto
     */
    @Override
    public void saveFollowBehavior(FollowBehaviorDto followBehaviorDto) {

        //只有用户类型才可以添加用户行为
        //判断是否为匿名账号
        //实体id
        Integer enteyId = followBehaviorDto.getUserId();
        //默认设置为用户
        int type = SystemConstants.TYPE_USER;
        //为匿名账号
        if(enteyId == SystemConstants.ANONYMOUS_USER_ID){
            //设置为设备类型
            type = SystemConstants.TYPE_E;
            //实体为匿名账号id
            enteyId = followBehaviorDto.getEquipmentId();
        }
        //根据用户id 和 类型查询行为实体
        ApBehaviorEntry entry = apBehaviorEntryMapper.findByEntryIdAndType(enteyId, type);
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        if(null == entry){
            //创建行为实体
            //暂时放着  应该放在用户登录就创建行为实体
            apBehaviorEntry.setType(type);
            apBehaviorEntry.setEntryId(enteyId);
            apBehaviorEntry.setCreatedTime(LocalDateTime.now());
            apBehaviorEntryMapper.insert(apBehaviorEntry);
        }
        //假设一定有实体
        if (true){
//        if (null != entry){
            //没有则添加,有用户才可以添加关注行为
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            //行为实体id
            apFollowBehavior.setEntryId(enteyId);
            apFollowBehavior.setArticleId(followBehaviorDto.getArticleId());
            //关注者id
            apFollowBehavior.setFollowId(enteyId);
            apFollowBehavior.setCreatedTime(LocalDateTime.now());
            save(apFollowBehavior);
        }


    }
}
